package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.RequestAddFriendActivity;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CommonBean;
import com.beiing.tianshuai.tianshuai.entity.PersonalDataCardBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.PersonalDataCardPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.PersonalDataCardViewImpl;
import com.beiing.tianshuai.tianshuai.nim.session.SessionHelper;
import com.beiing.tianshuai.tianshuai.widget.ActionSheet;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

/**
 * 用户详细资料卡片
 *
 * 详细资料
 */
public class PersonalDataCardActivity extends BaseActivity implements PersonalDataCardViewImpl, ActionSheet.OnSheetItemClickListener {

    @BindView(R.id.ll_dynamic)
    LinearLayout mDynamicContainer;
    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.civ_user_avatar)
    CircleImageView mCivUserAvatar;
    @BindView(R.id.tv_user_nickname)
    TextView mTvUserNickname;
    @BindView(R.id.tv_user_number)
    TextView mTvUserNumber;
    @BindView(R.id.tv_user_phone)
    TextView mTvUserPhone;
    @BindView(R.id.tv_user_email)
    TextView mTvUserEmail;
    @BindView(R.id.tv_user_university)
    TextView mTvUserUniversity;
    @BindView(R.id.btn_add_contact)
    TextView mBtnAddContact;
    @BindView(R.id.btn_start_chat)
    TextView mBtnStartChat;
    @BindView(R.id.tv_user_sign)
    TextView mTvUserSign;
    @BindView(R.id.toolbar_btn_menu)
    TextView mToolbarMenu;
    @BindView(R.id.iv_dynamic_pic_1)
    ImageView mIvDynamicPic1;
    @BindView(R.id.iv_dynamic_pic_2)
    ImageView mIvDynamicPic2;
    @BindView(R.id.iv_dynamic_pic_3)
    ImageView mIvDynamicPic3;
    @BindView(R.id.iv_dynamic_pic_4)
    ImageView mIvDynamicPic4;
    @BindView(R.id.iv_dynamic_pic_5)
    ImageView mIvDynamicPic5;

    private Context                                         mContext;
    private Unbinder                                        mUnbinder;
    private String                                          toUid;
    private boolean                                         isFriend;
    private PersonalDataCardBean.DataBean.UserInfoBean      mUserInfo;
    private PersonalDataCardPresenter                       mPresenter;
    private List<ImageView>                                 mImageViews;

    public static void star(Context context, String toUid) {
        Intent intent = new Intent(context, PersonalDataCardActivity.class);
        intent.putExtra("uid", toUid);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_data_card;
    }

    @Override
    protected void init() {
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        Intent intent = getIntent();
        toUid = intent.getStringExtra("uid");
        mImageViews = new ArrayList<>();
        mImageViews.add(mIvDynamicPic1);
        mImageViews.add(mIvDynamicPic2);
        mImageViews.add(mIvDynamicPic3);
        mImageViews.add(mIvDynamicPic4);
        mImageViews.add(mIvDynamicPic5);
        initToolbar();
        initPresenter();
        initListener();
    }

    private void initToolbar() {
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mToolbarTvTitle.setText("详细资料");
    }

    private void initView() {
        try {
            if (isFriend) {
                mBtnStartChat.setVisibility(View.VISIBLE);
                mToolbarMenu.setVisibility(View.VISIBLE);
                mBtnAddContact.setVisibility(View.GONE);
            } else {
                if (UserInfoBean.getUid(mContext).equals(toUid)) {
                    mBtnStartChat.setVisibility(View.GONE);
                    mBtnAddContact.setVisibility(View.GONE);
                    mToolbarMenu.setVisibility(View.GONE);
                } else {
                    mBtnStartChat.setVisibility(View.GONE);
                    mBtnAddContact.setVisibility(View.VISIBLE);
                    mToolbarMenu.setVisibility(View.GONE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        CustomProgressDialog.stopLoading();
    }

    private void initPresenter() {
        mPresenter = new PersonalDataCardPresenter(this);
        mPresenter.getPersonalInfoBean(toUid);
    }

    private void initListener() {
        // 活动
        mDynamicContainer.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", toUid);
                startActivity(intent);
            }
        });

        // 个人资料界面菜单
        mToolbarMenu.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                showMenu();
            }
        });

        // 开始聊天
        mBtnStartChat.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (mUserInfo != null) {
                    SessionHelper.startP2PSession(mContext, toUid);
                }
            }
        });

        // 添加好友
        mBtnAddContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, RequestAddFriendActivity.class);
                intent.putExtra("uid", toUid);
                intent.putExtra("nickname", mTvUserNickname.getText().toString());
                startActivity(intent);
            }
        });
    }

    // 底部弹出菜单
    private void showMenu() {
        ActionSheet actionSheet = new ActionSheet(mContext);
        if (isFriend) {
            actionSheet.builder()
                    .setCancelable(true)
                    .setCanceledOnTouchOutside(true)
                    // 菜单条目内容
                    .addSheetItem("删除", ActionSheet.SheetItemColor.Blue, this)
                    .show();
        } else {
            actionSheet.builder()
                    .setCancelable(true)
                    .setCanceledOnTouchOutside(true)
                    // 菜单条目内容
                    .addSheetItem("屏蔽", ActionSheet.SheetItemColor.Blue, this)
                    .show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在请求，请稍后...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(PersonalDataCardBean bean) {
        PersonalDataCardBean.DataBean data = bean.getData();
        try {
            mUserInfo = data.getUserinfor().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String photo = mUserInfo.getPhoto();
        mTvUserNickname.setText(TextUtils.isEmpty(mUserInfo.getName()) ? "" : mUserInfo.getName());
        RequestOptions requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .override(350, 350);
        Glide.with(mContext.getApplicationContext())
                .load(TextUtils.isEmpty(
                        photo) ?
                        R.mipmap.default_avatar :
                        HttpRequestConstant.USER_PIC_HEAD + photo)
                .apply(requestOptions)
                .into(mCivUserAvatar);
        mTvUserUniversity.setText(TextUtils.isEmpty(mUserInfo.getUnit()) ? "" : mUserInfo.getUnit());
        mTvUserSign.setText(TextUtils.isEmpty(mUserInfo.getSign()) ? "" : mUserInfo.getSign());
        mTvUserNumber.setText(MessageFormat.format("ID:{0}", mUserInfo.getId()));
        mTvUserEmail.setText(TextUtils.isEmpty(mUserInfo.getEmail()) ? "" : mUserInfo.getEmail());
        mTvUserPhone.setText(TextUtils.isEmpty(mUserInfo.getTel()) ? "" : mUserInfo.getTel());
        List<PersonalDataCardBean.DataBean.PicBean> pic = data.getPic();
        RequestOptions dynamicOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .override(400, 400);
        for (int i = 0; i < pic.size() && i < 5; i++) {
            PersonalDataCardBean.DataBean.PicBean picBean = pic.get(i);
            String picName = picBean.getPicname();
            Glide.with(mContext.getApplicationContext())
                    .load(TextUtils.isEmpty(
                            picName) ?
                            R.mipmap.default_avatar :
                            HttpRequestConstant.DYNAMIC_PIC_HEAD + picName)
                    .apply(dynamicOptions)
                    .into(mImageViews.get(i));
        }
        mPresenter.isFriend(UserInfoBean.getUid(mContext), toUid);
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("网络异常");
    }

    @Override
    public void isFriend(CommonBean bean) {
        isFriend = bean.getCode() != 200;
        initView();
    }

    @Override
    public void getDelFriendResult(CommonBean bean) {
        if (bean.getCode() == 200) {
            isFriend = false;
            initView();
        } else {
            showShortText("删除失败");
        }
    }

    @Override
    public void onClick(int which) {
        // 按照菜单条目添加时的position来进行点击事件的处理
        // 判断主页是否为当前用户主页
        if (isFriend) {
            switch (which) {
                case 1:
                    mPresenter.getDelFriendRequestResult(UserInfoBean.getUid(mContext), toUid);
                    break;
                    default:break;
            }
        } else {
            switch (which) {
                case 1:
                    break;
                default:break;

            }
        }
    }
}
